package com.miraclesea.module.rbac.test;

import static org.hamcrest.CoreMatchers.is;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

import org.springframework.test.web.servlet.ResultActions;

public final class RoleAsserter {
	
	private RoleAsserter() { }
	
	public static void assertPage(final ResultActions actual, final int expectedSize, final int expectedNumber, final long expectedTotal, 
			final int expectedAssignedPermissionCount, final int expectedDeniedPermissionCount) throws Exception {
		Long expectedTotalPages = expectedTotal % expectedSize == 0 ? expectedTotal / expectedSize : expectedTotal / expectedSize + 1;
		actual
			.andExpect(jsonPath("$.size", is(expectedSize)))
			.andExpect(jsonPath("$.number", is(expectedNumber)))
			.andExpect(jsonPath("$.totalPages", is(expectedTotalPages.intValue())));
		for (int i = 0; i < expectedSize; i++) {
			actual
				.andExpect(jsonPath(String.format("$.content[%s].id", i), is(String.format(RoleBuilder.ID, i))))
				.andExpect(jsonPath(String.format("$.content[%s].name", i), is(String.format(RoleBuilder.NAME, i))))
				.andExpect(jsonPath(String.format("$.content[%s].createdDate", i), is(0)))
				.andExpect(jsonPath(String.format("$.content[%s].lastModifiedDate", i), is(0)));
			for (int j = 0; j < expectedAssignedPermissionCount; j++) {
				actual.andExpect(jsonPath(String.format("$.content[%s].assignedPermissions[%s].permissionName", i, j), 
						is(String.format(RoleBuilder.ASSIGNED_PERMISSION_NAME, j, i))));
			}
			for (int j = 0; j < expectedDeniedPermissionCount; j++) {
				actual.andExpect(jsonPath(String.format("$.content[%s].deniedPermissions[%s].permissionName", i, j), 
						is(String.format(RoleBuilder.DENIED_PERMISSION_NAME, j, i))));
			}
		}
	}
	
	public static void assertRole(
			final ResultActions actual, final String appendix, final int expectedAssignedPermissionCount, final int expectedDeniedPermissionCount) throws Exception {
		actual
			.andExpect(jsonPath("$.id", is(String.format(RoleBuilder.ID, appendix))))
			.andExpect(jsonPath("$.name", is(String.format(RoleBuilder.NAME, appendix))))
			.andExpect(jsonPath("$.createdDate", is(0)))
			.andExpect(jsonPath("$.lastModifiedDate", is(0)));
		for (int i = 0; i < expectedAssignedPermissionCount; i++) {
			actual.andExpect(jsonPath(String.format("$.assignedPermissions[%s].permissionName", i), 
					is(String.format(RoleBuilder.ASSIGNED_PERMISSION_NAME, i, appendix))));
		}
		for (int i = 0; i < expectedAssignedPermissionCount; i++) {
			actual.andExpect(jsonPath(String.format("$.deniedPermissions[%s].permissionName", i), 
					is(String.format(RoleBuilder.DENIED_PERMISSION_NAME, i, appendix))));
		}
	}
}
